#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题:字符串开头或结尾匹配
问题: 你需要通过指定的文本模式去检查字符串的开头或者结尾，比如文件名后缀，URL Scheme等等。
提示 : 
"""
import os
from urllib.request import urlopen

url = 'http://www.python.org'


def recipe1():
    """使用 str.startswith() 或者是 str.endswith() 方法"""
    filename = 'spam.txt'
    print(f"{filename = }")
    print(f"{filename.endswith('.txt') = }")
    print(f"{filename.startswith('file:') = }")
    print(f"{url.startswith('http://') = }")


def recipe2():
    """多种匹配"""
    filenames = os.listdir('.')
    print(f"{filenames = }")
    print(f"{[name for name in filenames if name.endswith(('.c', '.h'))] = }")
    print(f"{any(name.endswith('.py') for name in filenames) = }")


def recipe3():
    """元组作为参数"""
    choices = ['http://', 'ftp:']
    print(f"{choices = }")
    # print(url.startswith(choices)) # TypeError
    print(f"{url.startswith(tuple(choices)) = }")


def recipe4():
    """使用切片来实现"""
    filename = 'span.txt'
    print(f"{filename = }")
    print(f"{filename[-4:] == '.txt' = }")
    print(f"{url[:5] == 'http:' or url[:6] == 'https:' or url[:4] == 'ftp:' = }")


def recipe5():
    """使用正则表达式去实现"""
    import re
    print(f"{re.match('http:|https:|ftp:', url) = }")


def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()
    print('recipe4'.center(20, '*'))
    recipe4()
    print('recipe5'.center(20, '*'))
    recipe5()


def read_data(name):
    if name.startswith(('http:', 'https:', 'ftp:')):  # 元组作为参数
        return urlopen(name).read()
    else:
        with open(name) as f:
            return f.read()


if __name__ == '__main__':
    main()
